import { MD } from "../../GMDBase/MD";
import GameConn from "../../GMDWeakNetGameBase/GameConn";
import QWEvent from "../../GMDBase/QWEvent";
import NSLoader from "../../GMDWeakNetGameBase/NSLoader";
import LCData from "../../GMDWeakNetGameBase/LCData";
import fbAccount from "../fbAccount";
import Login from "../../GMDWeakNetGameBase/Login";
import FB from "../FB";
import { gcfg } from "../../../gcfg";
import QWEventDispatcher from "../../GMDBase/QWEventDispatcher";
import BroadcastMgr from "./BroadcastMgr";

let canvas = null;
export default class ShareUtil
{
     //好友列表改变
     public static OnFriendChanged = "OnFriendChanged"


      

     public static getImgBase64(_texture:cc.Texture2D) {
        let width = 720, height = 375;
        if(!canvas) canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        let image = _texture.getHtmlElementObj();
        ctx.drawImage(image, 0, 0);
    
        return canvas.toDataURL('image/png');
    }

 

      //监听事件
    public static addEventListener(type: string, listener, owner = null) {
        ShareUtil.m_Evts.addEventListener(type, listener, owner)
    }
      
    //我推荐进入游戏的玩家队列
    public static get FList():any
    {
        return LCData.GetJson(LCData.ParamName.FList)
    }

    public static RegParams()
    {
        //追加需要监听变动的值 
        var ParamName = gcfg["ParamName"]
        ParamName["FList"] = "FList"//我推荐的角色列表 {id:{icon:<>,name:<>},...}
    }


    public static Go() {

        ShareUtil.RegParams()
        

        //登录成功的时候
        Login.Singletion.addEventListener(
            Login.OnLoginSuccess,
            (evt: QWEvent) => {
                cc.log("ShareUtil LoginSuccess")
                //提交推荐人信息给服务器 
                ShareUtil.UploadReferrals(); 
            },
            this
        ) 


        

        //监听好友列表变化
        LCData.addEventListener(LCData.OnValueChanged,(evt:QWEvent)=>{
            var key = evt.details
            if(key!="FList") return
            
            if(MD.Player.CanUseLocalData)
            {
                ShareUtil.m_Evts.dispatchEvent(new QWEvent(ShareUtil.OnFriendChanged))
            }else
            {
                Login.Singletion.WaitCanUseLocalData(
                {
                    showLoading: false,
                    success: () => {
                        ShareUtil.m_Evts.dispatchEvent(new QWEvent(ShareUtil.OnFriendChanged))
                    }
                }
                )
            }
        })

        //监听显示事件
        /*
        wx.onShow(
            (launchOption:any)=>{
                InviteFriends.DoLaunch(launchOption)
            }
        )*/
        
        //处理启动参数 
        /*
        FB.getEntryPointAsync()
        .then(
            entrypoint => {
                ShareUtil.DoLaunch(entrypoint) 
            }
        ); */

        

    }
    

    public static Go2()
    {
        var entrypointData = FB.getEntryPointData()
        console.log("===========entrypointData======",entrypointData)
        ShareUtil.DoLaunch(entrypointData) 


        if(FB.InFB)
        {
            if(entrypointData && entrypointData.type && entrypointData.type == 'switch_game')
            {
                FB.logEvent("game_switch_form_uc",null,{name: entrypointData.name, act_appid: entrypointData.appid})
            }

           
            var newPlayer = LCData.GetNumber(LCData.ParamName.FROM_LOG)==0
            if(newPlayer) LCData.Set(LCData.ParamName.FROM_LOG,"1")

            var point:string = FBInstant.context.getType()
            switch(point)
            {
                case "THREAD"://分享进入
                case "GROUP"://分享群进入
                    if(newPlayer)
                        FB.logEvent("from_share",1,{type:'new'})
                    else
                        FB.logEvent("from_share",1,{type:'old'})
                    break
                //case "SOLO":
                case "POST":
                    if(newPlayer)
                        FB.logEvent("from_tl_share",1,{type:'new'})
                    else
                        FB.logEvent("from_tl_share",1,{type:'old'})
                    break
            }
            
            
        }
    }

    //是否禁止分享
    public static get DisabledShare()
    {
        return false//!(wx.IsQWDev||MD.ServerList.FuncBoolValue("OpenShare", true))
    }


    
    static DoLaunch(query)
    {
        cc.log("======launchOption====",query)
        if(query)//存在启动参数
        {
            var openId = query["id"]//推荐人
            if(openId)//存在有效的推荐人
            { 
                cc.log("记录推荐参数 openId",openId)
                LCData.Set( "ReferralsOpenId",openId)
                LCData.Set( "ReferralsState","0")//推荐状态，尚未上传
                
                ShareUtil.UploadReferrals()//上传
            }
        }
    }


        
    //上传推荐者信息
    public static UploadReferrals()
    {
        if(!MD.LoginOK) return//没有登录成功
        

        cc.log("开始上传推荐人信息")
        var referralsOpenId = LCData.Get("ReferralsOpenId")
        if(!referralsOpenId) 
        {
            cc.log("不存在推荐人信息，跳过上传") 
            return
        }

        var state = LCData.GetNumber("ReferralsState")
        if(state>=2) 
        { 
            cc.log("已经上传完成，跳过上传") 
             return//已经上传完成了
        }

        //自动上传用户信息
        fbAccount.AutoUploadUserInfo()

        var name = LCData.Get(LCData.ParamName.NICK_NAME)
        var icon = LCData.Get(LCData.ParamName.AVATOR_URL)
        if(state==1)//已经上传过了基本信息
        {
            if(!name||!icon) return//不满足上传条件
        }

        var nm = {
            n:"UploadShareInfo",
            oid:referralsOpenId
        }

        if(name&&icon)
        {
            nm["name"] = name
            nm["icon"] = icon
        }

       

        cc.log("提交推荐人信息",nm)
        var loader = GameConn.Singletion.CreateLoader(nm)
            loader.addEventListener(NSLoader.OnComplete,
            (evt:QWEvent)=>{
                var data = evt.details
                if(data.r!=0) {
                    cc.log("上传分享信息遇到问题！")
                    return
                }

                cc.log("成功上传分享信息！") 

                //上传成功标记
                LCData.Set("ReferralsState",name&&icon?"2":"1")
            },
            this
            ) 
    }

    static m_Evts: QWEventDispatcher = new QWEventDispatcher()
}